package library.persistence.impl;

import library.domain.Message;
import library.persistence.DBUtil;
import library.persistence.dao.MessageDao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MessageDaoImpl implements MessageDao {
    private  static final String FIND_ALL_MESSAGE = "SELECT * FROM message";

    private static final String INSERT_MESSAGE =
            "INSERT INTO message (username,time,comment) VALUES(?,?,?)";

    private static final String DELETE_MESSAGE_BY_TIME = "DELETE FROM message WHERE time=?";

    public void insertMessage(Message message) {
        Connection connection = DBUtil.getConnection();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(INSERT_MESSAGE);
            preparedStatement.setString(1,message.getUsername());
            preparedStatement.setString(2, message.getTime());
            preparedStatement.setString(3,message.getComment());
            preparedStatement.execute();

            DBUtil.closePreparedStatement(preparedStatement);
            DBUtil.closeConnection(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<Message> getAllMessage(){
        List<Message> messageList = new ArrayList<>();

        Connection connection = DBUtil.getConnection();
        try{
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(FIND_ALL_MESSAGE);
            while(resultSet.next()){
                String username = resultSet.getString(1);
                String time = resultSet.getString(2);
                String comment = resultSet.getString(3);
                messageList.add(new Message(username,time,comment));
            }
            DBUtil.closeResultSet(resultSet);
            DBUtil.closeStatement(statement);
            DBUtil.closeConnection(connection);
        }catch (SQLException e) {
            e.printStackTrace();
        }
        return messageList;
    }

    public void deleteMessageByTime(String time){
        Connection connection = DBUtil.getConnection();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(DELETE_MESSAGE_BY_TIME);
            preparedStatement.setString(1,time);
            preparedStatement.execute();
            DBUtil.closePreparedStatement(preparedStatement);
            DBUtil.closeConnection(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
